package com.weiquan.interceptor;

import com.alibaba.fastjson2.JSON;
import com.weiquan.common.Result;
import com.weiquan.common.ResultCode;
import com.weiquan.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证拦截器
 * 
 * @author weiquan
 * @since 2024-01-01
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Value("${weiquan.jwt.header}")
    private String tokenHeader;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 获取token
        String token = getTokenFromRequest(request);
        
        if (!StringUtils.hasText(token)) {
            writeErrorResponse(response, ResultCode.UNAUTHORIZED);
            return false;
        }

        // 验证token
        if (!jwtUtils.validateToken(token)) {
            writeErrorResponse(response, ResultCode.TOKEN_INVALID);
            return false;
        }

        // 获取用户ID并设置到请求属性中
        Long userId = jwtUtils.getUserIdFromToken(token);
        if (userId == null) {
            writeErrorResponse(response, ResultCode.TOKEN_INVALID);
            return false;
        }

        request.setAttribute("userId", userId);
        return true;
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(tokenHeader);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 写入错误响应
     */
    private void writeErrorResponse(HttpServletResponse response, ResultCode resultCode) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        
        Result<Object> result = Result.error(resultCode);
        response.getWriter().write(JSON.toJSONString(result));
    }
}